package com.ycy.redisson;

import org.redisson.Redisson;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.TimeUnit;

/**
 * 红锁
 */
public class RedLockDemo {

  public static void main(String[] args) {
    Config config = new Config();
    config.useSingleServer().setAddress("redis://192.168.1.6:8000");
    RedissonClient redissonClient = Redisson.create(config);

    //锁设置过期时间防止了死锁，但是设置多久，设置短了，解锁会出问题，所以 redisson实现自动续命的锁。缺点：有单机问题
    RLock rLock =  redissonClient.getLock("syn");

    //但是Rlock有单机问题，

//    RedissonRedLock redissonRedLock = new RedissonRedLock(rLock1,rLock2,rLock3,rLock4,rLock5);
    RedissonRedLock redissonRedLock = new RedissonRedLock(rLock);
    try {
      redissonRedLock.lock(10, TimeUnit.SECONDS);
      System.out.println("do work");
      Thread.sleep(10000);
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      redissonRedLock.unlock();
    }

    System.out.println("finshed");

  }



}
